package floodFill;

public class Solution {
    boolean[][] used;
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        used = new boolean[image.length][image[0].length];
        bfs(image,sr,sc,newColor,image[sr][sc]);
        return image;
    }
    private void bfs(int[][] image,int sr,int sc,int newColor,int targetColor) {
        if (sr<0||sc<0||sr>=image.length||sc>=image[0].length) return;
        if(used[sr][sc])return;
        used[sr][sc] = true;
        if(image[sr][sc] == targetColor) {
            image[sr][sc] = newColor;
            bfs(image,sr+1,sc,newColor,targetColor);
            bfs(image,sr-1,sc,newColor,targetColor);
            bfs(image,sr,sc+1,newColor,targetColor);
            bfs(image,sr,sc-1,newColor,targetColor);
        }
    }
}
